<?php

class sbIsratel {

    public function connect($type = null) {
        if ($type == sbValues::CIVIC) {
            $url = sbValues::URL_NIS_ISRATEL;
        } else {
            $url = sbValues::URL_USD_ISRATEL;
        }

        $client = new SoapClient($url, array('trace' => 1));
        $ts = date('c');
        $headerbody = array(
            'UserIdentification' => array(
                'AgentNumber' => "3820125",
                'AgentIdToken' => "TAID=pCjGdk1zviQicNvSVWNgz63m0dUkTLtVZYtHRC0OAnU=",
                'UserName' => "Travis",
            ),
            'TimeStamp' => $ts
        );
        $ns = 'http://isrotel-services.com/agentsws/1.0/service';
        $header = new SOAPHeader($ns, 'ServiceSoapHeader', $headerbody);
        $client->__setSoapHeaders($header);

        return $client;
    }

    public function search($client, $hotel_code, $date, $days, $rooms) {
        return $client->Search(array(
                    'SearchObjectType' => 'Hotel',
                    'SearchObjectCode' => $hotel_code,
                    'ArrivalDate' => $date,
                    'StayNights' => $days,
                    'RoomGuests' => array(
                        'AdultsCount' => 1,
                        'ChildrenCount' => 0,
                        'BabiesCount' => 0
                    ),
                    'SearchOptions' => array(
                        'IncludeHotelInfo' => false,
                        'IncludePackageInfo' => true,
                        'IncludeRoomInfo' => false
                    )
        ));
    }

    public function getReservationParams($client, $token) {
        return $client->GetReservationParams(array(
                    'SearchResultToken' => $token,
                    'IncludePriceOptions' => true,
                    'IncludeParamTitles' => false
        ));
    }

    public function parseReservationParams($result) {
        if ($result->Status == 'SUCCESS') {
            return array(
                'price' => $result->Price,
                'token' => $result->ReservationParamsSignature
            );
        } else {
            return false;
        }
    }

    public function makeReservation($client, $token, $session, $guest) {
        return $client->MakeReservation(array(
                    'SearchResultToken' => $session,
                    'ReservationParamsSignature' => $token,
                    'Customer' => array('Passport' => $guest['passport_id'], 'Name' => array('FirstName' => $guest['first_name'], 'LastName' => $guest['last_name'])),
                    'Guarantee' => array('EmptyVoucher' => '')
        ));
    }

    public function parseMakeReservation($result) {
        if ($result->Status == 'SUCCESS') {
            return array(
                'reservation_id' => $result->PrimaryReservationId,
                'reservation_stirng' => simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA)
            );
        } else {
            return false;
        }
    }

    public function parseSearchResult($result) {
        if ($result->Status == 'SUCCESS') {
            $rooms = array();
            foreach ($result->AvailableHotels->Hotel->Rooms->Room as $r) {
                $codeRoom = $r->Code;
                $vacancies = $r->Vacancies;
                if (count($r->Boards->Board) > 1) {
                    $temp = array(
                        'room_code' => $codeRoom,
                        'bar_price_usd' => $r->Boards->Board[0]->Price->Price,
                        'vacancies' => $vacancies,
                        'key' => $r->Boards->Board[0]->Price->SearchResultToken
                    );
                } else {
                    $temp = array(
                        'room_code' => $codeRoom,
                        'bar_price_usd' => $r->Boards->Board->Price->Price,
                        'vacancies' => $vacancies,
                        'key' => $r->Boards->Board->Price->SearchResultToken
                    );
                }
                array_push($rooms, $temp);
            }
            return $rooms;
        } else {
            return null;
        }
    }

    public function repository($client) {
        return $client->GetRepository(array(
                    'Options' => array(
                        'RegionsOption' => 'BaseInfo',
                        'HotelsOption' => 'CodesOnly',
                        'RoomsOption' => 'CodesOnly',
                        'HotelFacilitiesOption' => 'BaseInfo',
                        'RoomFacilitiesOption' => 'BaseInfo',
                        'BoardsOption' => 'BaseInfo',
                        'VacationsOption' => 'BaseInfo',
                        'CreditCardTypesOption' => 'BaseInfo',
                        'ReservationSpecialRequestsOption' => 'BaseInfo'
                    ))
        );
    }

    public function searchByRegion($client, $region) {
        return $client->Search(array(
                    'SearchObjectType' => 'Region',
                    'SearchObjectCode' => $region,
                    'ArrivalDate' => '2014-05-25',
                    'StayNights' => 1,
                    'RoomGuests' => array(
                        'AdultsCount' => 2,
                        'ChildrenCount' => 0,
                        'BabiesCount' => 0
                    ),
                    'SearchOptions' => array(
                        'IncludeHotelInfo' => false,
                        'IncludePackageInfo' => true,
                        'IncludeRoomInfo' => true
                    )
        ));
    }

    public function parseSearchByRegion($result, $city, $stars) {
        $xml = $result;

        $arrHotels = array();
        if ($xml->Status == 'SUCCESS') {
            foreach ($xml->AvailableHotels->Hotel as $h) {
                $hotel_id = $h->Code;
                $arrRooms = array();
                foreach ($h->Rooms as $r) {
                    array_push($arrRooms, $this->parseRoomsSearchByRegion($r));
                }
                $arrHotels[$hotel_id] = $arrRooms[0];
            }
        }

        return $arrHotels;
    }
    
    public function insertLocalData($result, $city) {
        $keys = array_keys($result);

        $prices = array();

        foreach ($keys as $k) {
            $hotel = $this->hotelInfoByProviderCode($k);
            if (!is_null($hotel)) {
                $prices[$hotel['id']]['Hotel'] = $hotel;
                $prices[$hotel['id']]['Hotel']['Rooms'] = $this->insertRooms($result[$k]);
            }
        }

        $noprices = $this->insertNotAvailableHotels($prices, $city);

        $localprice = array();
        foreach ($noprices['sort_name'] as $h) {
            $localprice['sort_name'][$h['id']]['Hotel'] = $h;
        }
        
        foreach ($noprices['sort_rate'] as $h) {
            $localprice['sort_rate'][$h['id']]['Hotel'] = $h;
        }

        return array('search' => $prices, 'local_name' => $localprice['sort_name'], 'local_rate' => $localprice['sort_rate']);
    }
    
    private function hotelInfoByProviderCode($id) {
        $hotel = tblHotelTable::getInstance()->findByDql('provider_code=?', $id)->getFirst();
        if ($hotel) {
            return $hotel->toArray();
        } else {
            return null;
        }
    }
    
    private function roomInfoByProviderCode($id) {
        $room = tblRoomsTable::getInstance()->findByDql('code_name=?', $id)->getFirst();
        if ($room) {
            return $room->toArray();
        } else {
            return null;
        }
    }
    
    private function insertRooms($data) {
        $rooms = array();

        foreach ($data as $r) {
            $room = $this->roomInfoByProviderCode($r['RoomID']);
            if (!is_null($room)) {
                $room['Price'] = array(
                    'session' => $r['Session'],
                    'bar_price_usd' => $r['RoomPrice'],
                    'bar_price_nis' => 0,
                    'meal_plane' => $r['MealPlan'],
                    'meal_name' => $r['MealPlanName'],
                    'max_room' => $r['MaxRoomsOfType']
                );
                array_push($rooms, $room);
            }
        }

        return $rooms;
    }
    
    private function insertNotAvailableHotels($hotels, $city) {
        $keys = array_keys($hotels);

        $where = 'provider_id=' . sbValues::PROVIDER_ISR . ' AND city_id=' . $city;

        foreach ($keys as $k) {
            $where .= ' AND id<>' . $k;
        }

        $objHotelsName = Doctrine_Query::create()->select('*')->from('tblHotel')->where($where)->orderBy('name_en ASC')->execute();
        $arrHotelsName = $objHotelsName->toArray();
        
        $objHotelsRate = Doctrine_Query::create()->select('*')->from('tblHotel')->where($where)->orderBy('stars DESC')->execute();
        $arrHotelsRate = $objHotelsRate->toArray();

        return array('sort_name' => $arrHotelsName, 'sort_rate' => $arrHotelsRate);
    }

    public function parseRoomsSearchByRegion($room) {
        $arrRooms = array();

        foreach ($room as $r) {
            $roomId = $r->Code;
            $vacancies = $r->Vacancies;

            foreach ($r->Boards as $b) {
                $size = count($b);
                if ($size > 1) {
                    foreach ($b as $bb) {
                        $temp = array(
                            'Session' => $bb->Price->SearchResultToken,
                            'RoomID' => $roomId,
                            'MealPlan' => $bb->Code,
                            'MealPlanName' => '',
                            'RoomPrice' => $bb->Price->Price,
                            'Currency' => $bb->Price->Currency,
                            'MaxRoomsOfType' => $vacancies
                        );

                        array_push($arrRooms, $temp);
                    }
                } else if ($size == 1) {
                    $temp = array(
                            'Session' => $b->Price->SearchResultToken,
                            'RoomID' => $roomId,
                            'MealPlan' => $b->Code,
                            'MealPlanName' => '',
                            'RoomPrice' => $b->Price->Price,
                            'Currency' => $b->Price->Currency,
                            'MaxRoomsOfType' => $vacancies
                        );

                        array_push($arrRooms, $temp);
                }
            }
        }

        return $arrRooms;
    }

}
